package com.llsydn.beijingnews.activity;

import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.Window;
import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;
import com.jeremyfeinstein.slidingmenu.lib.app.SlidingFragmentActivity;
import com.llsydn.beijingnews.R;
import com.llsydn.beijingnews.fragment.ContentFragment;
import com.llsydn.beijingnews.fragment.LeftmenuFragment;
import com.llsydn.beijingnews.util.DensityUtils;

/**
 * @author lilinshen
 * @title 主页面
 * @description 继承SlidingFragmentActivity，实现左右侧滑的效果。
 * @date 2018/10/24 17:27
 */
public class MainActivity extends SlidingFragmentActivity {

    public static final String MAIN_CONTENT_TAG = "main_content_tag";
    public static final String LEFT_MENU_TAG = "left_menu_tag";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        // 隐藏标题
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);
        // 初始化SlidingMenu
        initSlidingMenu();

        // 初始化Fragment
        initFragment();
    }

    /**
     * 初始化SlidingMenu
     */
    private void initSlidingMenu() {
        // 1.设置主页面
        setContentView(R.layout.activity_main);

        // 2.设置左侧菜单
        setBehindContentView(R.layout.activity_leftmenu);

        // 3.设置右侧菜单
        SlidingMenu slidingMenu = getSlidingMenu();
        slidingMenu.setSecondaryMenu(R.layout.activity_rightmenu);

        // 4.设置显示的模式：左侧菜单+主页(left)；左侧菜单+主页面+右侧菜单(left_right)；主页面+右侧菜单(right)
        slidingMenu.setMode(SlidingMenu.LEFT);

        // 5.设置滑动模式：滑动边缘，全屏滑动，不可滑动
        slidingMenu.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);

        // 6.设置主页面占居的宽度
        slidingMenu.setBehindOffset(DensityUtils.dip2px(MainActivity.this, 230));
    }

    /**
     * 初始化Fragment
     */
    private void initFragment() {
        // 1.得到FragmentManager
        FragmentManager fragmentManager = getSupportFragmentManager();

        // 2.开始事务
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

        // 3.替换
        fragmentTransaction.replace(R.id.fl_main_content, new ContentFragment(), MAIN_CONTENT_TAG);
        fragmentTransaction.replace(R.id.fl_left_menu, new LeftmenuFragment(), LEFT_MENU_TAG);

        // 4.提交
        fragmentTransaction.commit();
    }

    /**
     * 得到左侧菜单的fragment
     *
     * @return
     */
    public LeftmenuFragment getLeftmenuFragment() {
        return (LeftmenuFragment) getSupportFragmentManager().findFragmentByTag(LEFT_MENU_TAG);
    }

    /**
     * 得到正文的fragment
     *
     * @return
     */
    public ContentFragment getContentFragment() {
        return (ContentFragment) getSupportFragmentManager().findFragmentByTag(MAIN_CONTENT_TAG);
    }
}
